# import requests
# from lxml import etree
# import re
# import json
#
# myHeader = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'}
# # url = 'https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_web_new_fanyi&sign=koExfbNAVhXDlPtST9%2FxJ9RriqVIAJSQ%2BxmfU0q7dIE%3D'
# url = 'https://dict.youdao.com/webtranslate'
#
# dt = {
#     'from': 'auto',
#     'to': 'auto',
#     'q': '小英真可恶'
# }
#
# resp = requests.post(url, headers=myHeader, data=dt)
# # print(json.loads(resp.text)['message'])
# print(resp.text)

# !/usr/bin/env python
# -*- encoding: utf-8 -*-
# import requests
# import time
# import random
# from hashlib import md5
#
# headers = {
#     'Cookie': 'OUTFOX_SEARCH_USER_ID=-690213934@10.108.162.139; OUTFOX_SEARCH_USER_ID_NCOO=1273672853.5782404; fanyi-ad-id=308216; fanyi-ad-closed=1; ___rl__test__cookies=1659506664755',
#     'Host': 'fanyi.youdao.com',
#     'Origin': 'https://fanyi.youdao.com',
#     'Referer': 'https://fanyi.youdao.com/',
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
# }
# key = input("请输入你要翻译的单词：")
# lts = str(int(time.time() * 100))
# salt = lts + str(random.randint(0, 9))
# sign_data = 'fanyideskweb' + key + salt + 'Ygy_4c=r#e#4EX^NUGUc5'
# sign = md5(sign_data.encode()).hexdigest()
# data = {
#     'i': key,
#     'from': 'AUTO',
#     'to': 'AUTO',
#     'smartresult': 'dict',
#     'client': 'fanyideskweb',
#     # 时间戳  1970  秒
#     'salt': salt,
#     # 加密
#     'sign': sign,
#     # 时间戳
#     'lts': lts,
#     # 加密的数据
#     'bv': 'f0819a82107e6150005e75ef5fddcc3b',
#     'doctype': 'json',
#     'version': '2.1',
#     'keyfrom': 'fanyi.web',
#     'action': 'FY_BY_REALTlME',
# }
#
# # 获取到资源地址
# url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
# response = requests.post(url, headers=headers, data=data)
# print(response.text)

import hashlib
import base64
import time
import json
import js2py
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad, pad

headers = {
    # 'Accept': 'application/json, text/plain, */*',
    # 'Accept-Encoding': 'gzip, deflate, br',
    # 'Accept-Language': 'zh-CN,zh;q=0.9',
    # 'Connection': 'keep-alive',
    # 'Content-Length': '252',
    # 'Content-Type': 'application/x-www-form-urlencoded',
    'Cookie': 'OUTFOX_SEARCH_USER_ID=-128580344@10.169.0.83; OUTFOX_SEARCH_USER_ID_NCOO=1344989105.8974342; _ntes_nnid=9b83b473d066e2e23751e2d758891587,1641266653081; search-popup-show=-1; __yadk_uid=Uby0XrclZI18dTgSjb55uEGqfHqTXOfo',
    # 'Host': 'dict.youdao.com',
    # 'Origin': 'https://fanyi.youdao.com',
    'Referer': 'https://fanyi.youdao.com/',
    # 'Sec-Fetch-Dest': 'empty',
    # 'Sec-Fetch-Mode': 'cors',
    # 'Sec-Fetch-Site': 'same-site',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}


def make_request(word, to=''):
    form = {
        'from': 'auto',
        'to': to,
        'dictResult': 'true',
        'keyid': 'webfanyi',
        'client': 'fanyideskweb',
        'product': 'webfanyi',
        'appVersion': '1.0.0',
        'vendor': 'web',
        'pointParam': 'client,mysticTime,product',
        'keyfrom': 'fanyi.web'
    }

    r = 'fanyideskweb'
    i = 'webfanyi'
    e = 'fsdsogkndfokasodnaso'
    t = int(round(time.time() * 1000))

    p = f"client={r}&mysticTime={t}&product={i}&key={e}"
    sign = hashlib.md5(p.encode('utf8')).hexdigest()

    form['i'] = word
    form['sign'] = sign
    form['mysticTime'] = t

    url = 'https://dict.youdao.com/webtranslate'

    res = requests.post(url=url, headers=headers, data=form)

    return res.text


def translate(text, key, iv):
    iv = hashlib.md5(iv).digest()
    key = hashlib.md5(key).digest()

    # CBC模式解密
    AES_decrypt = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
    # 返回数据转为byte
    t = base64.b64decode(text, b'-_')
    # 解码
    decrypted_data = AES_decrypt.decrypt(t)
    # 解码数据拆分
    unpadded_message = unpad(decrypted_data, AES.block_size).decode()
    # 解码数据转为json数据结构
    json_data = json.loads(unpadded_message)
    # print(json_data)
    try:
        res = json_data['translateResult'][0][0]['tgt']
    except Exception as e:
        return unknown_msg

    return res


unknown_msg = ''

if __name__ == '__main__':
    decodekey = b'ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl'
    decodeIv = b'ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4'
    while True:
        user_input = input('我想翻译:')
        unknown_msg = user_input
        text = make_request(user_input, to='')
        print('翻译结果:' + translate(text, decodekey, decodeIv))
        isContinue = input('继续翻译吗？(Y/N)')
        if isContinue == 'Y' or isContinue == 'y':
            continue
        else:
            break
